import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const foodReducer = createSlice({
  name: "food",
  initialState: {
    foodsList: [], // 右侧商品列表
    activeIndex: 0, // 选中菜单的索引
    cartList: [], // 购物车数量
  },
  reducers: {
    setFoodsList(state, action) {
      state.foodsList = action.payload;
    },
    setActiveIndex(state, action) {
      state.activeIndex = action.payload;
    },
    addCart(state, action) {
      // 是否添加过
      /**
       * 是否添加过？以action.payload.id 去catList中匹配，匹配到就是添加过了
       */

      const item = state.cartList.find((item) => item.id === action.payload.id);

      if (item) {
        if (!item.count) {
          item.count = 0;
        }
        item.count++;
      } else {
        if (!action.payload.count) {
          action.payload.count = 1;
        }
        state.cartList.push(action.payload);
      }
    },

    // count增-购物车
    increCount(state, action) {
      const item = state.cartList.find((item) => item.id === action.payload.id);
      item.count++;
    },
    // count减-购物车
    decreCount(state, action) {
      const item = state.cartList.find((item) => item.id === action.payload.id);
      const itemIndex = state.cartList.findIndex(
        (item) => item.id === action.payload.id
      );
      item.count--;

      if (item.count === 0) {
        state.cartList.splice(itemIndex, 1);
      }
    },
    // 清除购物车
    clearCart(state) {
      state.cartList = [];
    },
  },
});

const {
  setFoodsList,
  setActiveIndex,
  addCart,
  decreCount,
  increCount,
  clearCart,
} = foodReducer.actions;
const reducer = foodReducer.reducer;

const fetchFoodsList = () => {
  return async (dispatch) => {
    const list = await axios.get("http://localhost:3004/takeaway");
    dispatch(setFoodsList(list.data));
  };
};

export {
  fetchFoodsList,
  setActiveIndex,
  addCart,
  decreCount,
  increCount,
  clearCart,
};
export default reducer;
